package com.example.mvvmdemo.data.network;

import com.example.mvvmdemo.BuildConfig;

import android.content.Context;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import okhttp3.OkHttpClient;

public abstract class CommonRetrofit<T> extends BaseRetrofit<T> {

    @Inject
    Context context;

    protected CommonRetrofit() {
    }

    protected Context getContext() {
        return context;
    }

    @Override
    protected String getBaseUrl() {
        return BuildConfig.SERVICE_API_URL;
    }

    @Override
    protected OkHttpClient.Builder okHttpClientHandler(OkHttpClient.Builder builder) {
        builder.connectTimeout(60, TimeUnit.SECONDS);
        builder.readTimeout(60, TimeUnit.SECONDS);
        builder.writeTimeout(60, TimeUnit.SECONDS);

        //TODO cookie 操作
//        builder.cookieJar(new CookieJar() {
//            @Override
//            public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
//                CookieManager cookieManager =
//                    CookieManager.getInstance();
//                for (Cookie cookie : cookies) {
//                    cookieManager.setCookie(url.toString(), cookie.toString());
//                }
//            }
//
//            @Override
//            public List<Cookie> loadForRequest(HttpUrl url) {
//                CookieManager cookieManager = CookieManager.getInstance();
//                List<Cookie> cookies = new ArrayList<>();
//                if (cookieManager.getCookie(url.toString()) != null) {
//                    String[] splitCookies = cookieManager.getCookie(url.toString()).split("[;]");
//                    for (String splitCooky : splitCookies) {
//                        cookies.add(Cookie.parse(url, splitCooky.trim()));
//                        Timber.v("OkHttp cookies: %s", splitCooky.trim());
//                    }
//                }
//                return cookies;
//            }
//        });
//        builder.addInterceptor(new CookiesSaveIntercepter(context));
//        builder.addInterceptor(new NetworkAvailabilityInterceptor(context));
        builder.addInterceptor(new RequestInterceptor(context));
        return super.okHttpClientHandler(builder);
    }
}
